#!/usr/bin/python
#coding=utf-8
import cv2 
import rospy
from cv_bridge import CvBridge
from sensor_msgs.msg import Image
from std_msgs.msg import String
from sensor_msgs.msg import RegionOfInterest as ROI
import pyzbar.pyzbar as pyzbar
# import numpy as np

rospy.init_node('qrcode', anonymous=False)
qrdata_pub=rospy.Publisher("qrcode_data",String,queue_size=1)
qrroi_pub=rospy.Publisher("qrcode_roi",ROI,queue_size=5)
cvb=CvBridge()

def callback(data):
    qrdata=String()
    roi_data=ROI()
    img=cvb.imgmsg_to_cv2(data,"bgr8")
    frame_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    barcodes = pyzbar.decode(frame_gray) 
    if len(barcodes)>0:
        for barcode in barcodes:
            barcodeData = barcode.data.decode("utf-8")
            roi_data.x_offset=barcode.rect.left
            roi_data.y_offset=barcode.rect.top
            roi_data.width=barcode.rect.width
            roi_data.height=barcode.rect.height
            if len(barcodeData) >= 1:
                qrdata_pub.publish(barcodeData)
                qrroi_pub.publish(roi_data)
def get_img():
    rospy.Subscriber("camera/rgb/image_raw", Image, callback)
    rospy.spin()

if __name__ == '__main__':
    print("二维码识别启动")
    try:
        get_img()      
    except rospy.ROSInterruptException:
        rospy.loginfo("qrcode node terminated.")

